﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Web;
using System.Configuration;
using System.DirectoryServices;

using H2.NET.Business;
using H2.NET.Data.Common;

namespace H2.NET
{
    public class Util
    {
        #region 取得配置相关 (AppSettings)
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string AppSettings(string strConn)
        {
            try
            {
                return ConfigurationManager.AppSettings.Get(strConn);
            }
            catch (Exception)
            {
                return "";
            }
        }
        #endregion

        #region 取得配置相关 (ConnectionStrings)
        /// <summary>
        /// 
        /// </summary>
        public static string ConnectionStrings(string strKey)
        {
            try
            {
                return ConfigurationManager.ConnectionStrings[strKey].ConnectionString;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region 取得配置相关 (SQL)
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string getConn2(string strConn)
        {
            string strLine = "";
            try
            {

                FileInfo fleInfo = new FileInfo(Util.AppSettings("sql"));
                StreamReader steReader = fleInfo.OpenText();
                bool booExist = false;
                do
                {
                    //从文本文件读取一行
                    strLine = "";
                    strLine = steReader.ReadLine();

                    //空白行时,退出循环
                    if (strLine == null)
                    {
                        break;
                    }

                    int intLoc = strLine.IndexOf('=');
                    int intLoc2 = strLine.Length - intLoc;
                    string strName = strLine.Substring(0, intLoc);
                    if (strName.ToUpper() == strConn.ToUpper())
                    {
                        strLine = strLine.Substring(intLoc + 1, intLoc2 - 1);
                        booExist = true;
                    }
                }
                while (!booExist);

                steReader.Close();

            }
            catch (Exception)
            {

            }

            return strLine;
        }
        #endregion

        #region 获取web.config中db 连接名
        /// <summary>
        /// 获取所有 db 连接名
        /// </summary>
        public static string AllConnectionStrings()
        {
            try
            {
                string strKey = "";
                for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
                {
                    if (ConfigurationManager.ConnectionStrings[i].Name == "LocalSqlServer")
                    {
                        continue;
                    }

                    strKey = strKey + (strKey == "" ? "" : "~") + ConfigurationManager.ConnectionStrings[i].Name;
                }
                return strKey;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region 加密字符串 (Encrypt)
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, "!234qwer");
        }
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        private static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.UTF8.GetBytes(Text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        #endregion

        #region 解密字符串 (Decrypt)
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text)
        {
            return Decrypt(Text, "!234qwer");
        }
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        private static string Decrypt(string Text, string sKey)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                int len;
                len = Text.Length / 2;
                byte[] inputByteArray = new byte[len];
                int x, i;
                for (x = 0; x < len; x++)
                {
                    i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                    inputByteArray[x] = (byte)i;
                }
                des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception)
            {
                return "";
            }
        }
        #endregion 

        #region 加解密字符 (简单)
        public static string Encode(string strCode)
        {
            try
            {
                string strEncode = "";

                for (int i = 0; i < strCode.Length; i++)
                {
                    string s = Convert.ToString((int)(strCode.Substring(i, 1).ToCharArray()[0]), 16);
                    if (s.Length == 4)
                    {
                        strEncode += s;
                    }
                    else
                    {
                        strEncode += "00" + s;
                    }
                }

                return strEncode.ToUpper();

            }
            catch (Exception)
            {
                return "";
            }
        }

        public static string Decode(string strCode)
        {
            try
            {
                string strDecode = "";

                for (int i = 0; i < strCode.Length; i = i + 4)
                {
                    strDecode += System.Convert.ToChar(Convert.ToInt64(strCode.Substring(i, 4), 16));
                }

                return strDecode;
            }
            catch (Exception)
            {
                return "";
            }
        }
        #endregion

        #region 设置Cookies信息
        /// <summary>
        /// 
        /// </summary>
        public static bool SetCookies(string strCookiesName, string strCookiesValue, DateTime dteValue)
        {
            try
            {
                HttpCookie cookies = new HttpCookie(strCookiesName, strCookiesValue);
                cookies.Expires = dteValue;
                HttpContext.Current.Response.Cookies.Add(cookies);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion

        #region 页面跳转 (javascript)
        /// <summary>
        /// 
        /// </summary>
        public static string GoToWebPath(string str_path)
        {
            try
            {
                string str_script = "";
                str_script += "<script type='text/javascript'>\n";
                str_script += "  this.parent.window.location='" + str_path + "';\n";
                str_script += "</script>\n";

                return str_script;
            }
            catch (Exception)
            {
                return "";
            }
        }
        #endregion

        #region 取序列编号
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Prefix"></param>
        /// <param name="Postfix"></param>
        /// <param name="Digits"></param>
        /// <returns></returns>
        public static string GenerateSequence(string Prefix, string Postfix, int Digits)
        {
            Prefix = Prefix == null ? "" : Prefix;
            Postfix = Postfix == null ? "" : Postfix;

            if ((t_Sequence.prefix == Prefix & t_Sequence.postfix == Postfix & t_Sequence.digits == Digits).Count<t_Sequence>(Storage.Context1) <= 0)
            {
                t_Sequence seq = new t_Sequence();
                seq.Prefix = Prefix;
                seq.Postfix = Postfix;
                seq.Digits = Digits;
                seq.No = 1;
                Storage.Save(Storage.Context1, seq);

                return Prefix + seq.No.ToString().PadLeft(Digits < 0 ? 0 : Digits, '0') + Postfix;
            }
            else
            {
                t_Sequence seq2 = (t_Sequence.prefix == Prefix
                    & t_Sequence.postfix == Postfix
                    & t_Sequence.digits == Digits).ListFirst<t_Sequence>(Storage.Context1, "[no] desc");

                t_Sequence new_seq = new t_Sequence();
                new_seq.Prefix = Prefix;
                new_seq.Postfix = Postfix;
                new_seq.Digits = Digits;
                new_seq.No = seq2.No + 1;

                Storage.Save(Storage.Context1, new_seq);

                return Prefix + new_seq.No.ToString().PadLeft(Digits < 0 ? 0 : Digits, '0') + Postfix;
            }
        }
        #endregion

        #region 判断文字长度(包括中文)
        public static int TextLength(string Text)
        {
            int len = 0;

            for (int i = 0; i < Text.Length; i++)
            {
                byte[] byte_len = System.Text.Encoding.Default.GetBytes(Text.Substring(i, 1));
                if (byte_len.Length > 1)
                    len += 2;  //如果长度大于1，是中文，占两个字节，+2
                else
                    len += 1;  //如果长度等于1，是英文，占一个字节，+1
            }

            return len;
        }
        #endregion

        #region 获取客户端ip
        public static string GetClientIP()
        {

            string result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (string.IsNullOrEmpty(result))
            {
                result = System.Web.HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }
        #endregion
    }
}
